package net.pimpas.report.processor.manager.impl;

import java.util.List;
import net.pimpas.report.processor.condition.Condition;
import net.pimpas.report.processor.exception.ReportProcessorExportException;
import net.pimpas.report.processor.exception.ReportProcessorImportException;
import net.pimpas.report.processor.manager.ReportProcessorManager;
import net.pimpas.report.processor.manager.ReportProcessorPersistence;
import net.pimpas.report.processor.projection.Projection;
import net.pimpas.report.processor.serviceprovider.ReportProcessorServiceProvider;
import net.pimpas.report.processor.serviceprovider.impl.ReportProcessorServiceProviderFactoryImpl;
import net.pimpas.report.processor.tree.Tree;
import net.pimpas.transformation.serviceprovider.exception.TransformationServiceProviderException;
import net.pimpas.transformation.xml.serviceprovider.XmlTransformationServiceProviderFactoryImpl;

import org.hibernate.criterion.DetachedCriteria;

public class ReportProcessorManagerImpl implements ReportProcessorManager {

	public ReportProcessorPersistence exportToBean(Tree tree, List<Condition> conditions, List<Projection> projections) throws ReportProcessorExportException {
		ReportProcessorPersistence bean = new ReportProcessorPersistence(tree, conditions, projections);
		
		return bean;
	}

	public String exportToXml(ReportProcessorPersistence processor) throws ReportProcessorExportException {
		try {
			return XmlTransformationServiceProviderFactoryImpl.getXmlTransformationServiceProvider()
			.to(processor);
		} catch (TransformationServiceProviderException e) {
			throw new ReportProcessorExportException(e);
		}
	}

	public DetachedCriteria importFromBean(ReportProcessorPersistence bean) throws ReportProcessorImportException {
		ReportProcessorServiceProvider rprocessor = 
			ReportProcessorServiceProviderFactoryImpl.getReportProcessorServiceprovider();
		
		try {
			Tree tree = rprocessor.createTree(bean.getTreeClass(), bean.getTreeName());
			return rprocessor.apply(tree, bean.getConditions(), bean.getProjections());
		} catch (Exception e) {
			throw new ReportProcessorImportException(e);
		}
	}

	public DetachedCriteria importFromXml(String xml) throws ReportProcessorImportException {
		ReportProcessorPersistence bean;
		try {
			bean = (ReportProcessorPersistence) XmlTransformationServiceProviderFactoryImpl.getXmlTransformationServiceProvider()
			.from(xml, ReportProcessorPersistence.class);
			return this.importFromBean(bean);
		} catch (TransformationServiceProviderException e) {
			throw new ReportProcessorImportException(e);
		}
	}
}